<?php
/**
 * (logic) （临时转正式）Payment-Total总额
 */
namespace App\Logic\MonthlyReport\ParseTmp;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Payment\PaymentTotal;
use App\Models\MonthlyReport\Tmp\TmpPTotal;
class ParsePaymentTotal
{
    public static function exeParse($date){
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        //临时
        $lines = [];
        TmpPTotal::query()->where('report_date',$date)
            ->whereNotNull('sku')
            ->select('country','sku','total')
            ->orderBy('id')
            ->chunk(2000, function ($items) use (&$lines){
                foreach ($items as $item){
                    $key = $item->country.'_'.$item->sku;
                    if(!array_key_exists($key,$lines)){
                        $lines[$key] = $item->total;
                    }else{
                        $lines[$key] += $item->total;
                    }
                }
            });

        $i = 0;
        $num = 500;
        $countryArr = [];
        while(true){
            if(empty($lines))break;
            $_lines = array_splice($lines,$i,$num);
            foreach ($_lines as $key => $total){
                list($country,$sku) = explode('_',$key);
                if(!array_key_exists($country,$countryArr)){
                    $countryId = SysCountry::getIdByCountry($country);
                    $countryArr[$country] = $countryId ?: 0;
                }
                //正式
                PaymentTotal::query()->updateOrCreate(['report_date' => $date,
                    'country_id' => $countryArr[$country],
                    'seller_sku' => $sku],
                    ['total' => $total]);
            }
        }
    }
}
